package com.example.demo.controller;

import com.example.demo.pojo.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//UDP数据接收类，通过将IP和端口号，建立websocket连接
@Component
@ServerEndpoint(value = "/chat/msg")
public class ChatEndpoint {
    //用来存储每个用户客户端对象的ChatEndpoint对象
    private static Map<String, ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();
    //声明session对象，通过对象可以发送消息给指定的用户
    private Session session;
    //接受UDP数据工具类
    //UDP组播数据端口和IP地址
    String IP = "224.100.1.8";
    int port = 6008;

    //    String IP = "224.100.1.8";
//    int port = 6008;
    //    建立连接时
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
//        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
//        this.httpSession = httpSession;
        //存储登陆的对象
//        String username = (String)httpSession.getAttribute("user");
        String username = "张三";
        onlineUsers.put(username, this);

        //将当前在线用户的用户名推送给所有的客户端
        //1 获取消息
//        String message = MessageUtils.getMessage(true, null, getNames());
        //2 调用方法进行系统消息的推送
//        String data = receiveUtils.receverMessage(IP, port);
        broadcastAllUsers("连接建立成功");
    }

    private void broadcastAllUsers(String message) {
        try {
            //将消息推送给所有的客户端
            Set<String> names = onlineUsers.keySet();
            for (String name : names) {
                ChatEndpoint chatEndpoint = onlineUsers.get(name);
                chatEndpoint.session.getAsyncRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public synchronized void onMessage(String message, Session session) {
        //将数据转换成对象
        try {
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(mapper);
            Message mess = mapper.readValue(message, Message.class);
//            String toName = mess.getToname();
            String toName = "张三";
            MulticastSocket socket = new MulticastSocket(port);
            boolean closed = false;
            InetAddress group = InetAddress.getByName(IP);
            socket.joinGroup(group);//加入组播地址
            byte[] receiveBuffer = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
            receivePacket.setPort(1234);
            while (!closed) {
                //send();
                socket.receive(receivePacket);
                byte[] data = receivePacket.getData();
                int offset = receivePacket.getOffset();
                int len = receivePacket.getLength();
//                数据转化为十六进制
                String msg = bytestohex(data, len);
                System.out.println(msg);
                synchronized (msg) {
//                    onlineUsers.get(toName).session.getAsyncRemote().sendText(msg);
                    session.getBasicRemote().sendText(msg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    将数据转化为十六进制,并将长度调整为60
    public String bytestohex(byte[] data, int len) {
        StringBuilder sb = new StringBuilder();
        String result="";
        for (int i = 0; i < len; i++) {
            sb.append(String.format("%02x ", data[i]));
        }
        String s =sb.toString();
        int i = s.length();
        if (i == 66) {
            result = s.substring(0, 60);
        } else if (i % 60 == 0 && i != 60) {
            for (int j = 0; j < i; j += 60) {
                result=s.substring(j, j + 60);
            }
        }else {
            result=s;
        }
        return result;
    }

    //    public String formatmsg(String msg){
//        msg.getChars(0,60,);
//    }
    //关闭
    @OnClose
    public void onClose(Session session) {
        String username = "张三";
//        String username = (String) httpSession.getAttribute("user");
        //从容器中删除指定的用户
        onlineUsers.remove(username);
//        MessageUtils.getMessage(true,null,getNames());
    }

}
